//
//  CocoaLocation.m
//  打工宝
//
//  Created by 中昊科技 on 15/6/3.
//  Copyright (c) 2015年 中昊科技. All rights reserved.
//    //    http://www.cnblogs.com/wayne23/p/3785900.html
//http://www.cocoachina.com/ios/20150618/12200.html  关于IOS 9 定位适配

#import "ZYLocationManager.h"


@implementation ZYLocationManager

+ (ZYLocationManager *)shareLocation
{
    static ZYLocationManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[ZYLocationManager alloc] init];
    });
    return manager;

}
- (instancetype)init {
    self = [super init];
    if (self) {
        _isAlwaysUse = NO;
        _isRealTime = NO;
        //  设置定位的精准度，一般精准度越高，越耗电（这里设置为精准度最高的，适用于导航应用）
        _desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    }
    return self;
}

-(CLLocationManager *)locationManager
{
    if (_locationManager == nil) {
        [UIApplication sharedApplication].idleTimerDisabled = TRUE;
        self.locationManager=[[CLLocationManager alloc]init];
    }
    return _locationManager;
}

-(void)getLoctionManager:(LocationBlock)loctionBlock;
{
    self.locationBlock = [loctionBlock copy];
    [self startLocatinManager];
}
// 停止更新位置（如果定位服务不需要实时更新的话，那么应该停止位置的更新）
-(void)stopLocation
{
    [self.locationManager stopUpdatingLocation];
    self.locationManager.delegate = nil;
}

-(void)startLocatinManager
{
//  判断用户定位服务是否开启    if ([CLLocationManager locationServicesEnabled] &&([CLLocationManager authorizationStatus] >=3))
    if ([CLLocationManager locationServicesEnabled]) {
        
//      控制定位服务更新频率。单位是“米”每隔多少米定位一次（这里的设置为任何的移动)
        if (self.distanceFilter == 0) {
            self.locationManager.distanceFilter = kCLDistanceFilterNone;
        }else{
            self.locationManager.distanceFilter = self.distanceFilter;
        }
        
        self.locationManager.desiredAccuracy = _desiredAccuracy;
        
        if ([UIDevice currentDevice].systemVersion.doubleValue >= 8) {
            if (_isAlwaysUse) {
                [self.locationManager requestAlwaysAuthorization]; //始终
//                [self.locationManager performSelector:@selector(requestWhenInUseAuthorization) withObject:nil afterDelay:0];
            }else{
                [self.locationManager requestWhenInUseAuthorization];   //使用期间
            }
        }
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
            if (_isAlwaysUse) {
                self.locationManager.allowsBackgroundLocationUpdates = YES;
            }
        }
    }else{
        NSError *error = [NSError errorWithDomain:@"定位失败！打开定位设置" code:1000000 userInfo:nil];
        self.locationBlock (nil,nil,error);
    }
    self.locationManager.delegate = self;
    [self.locationManager startUpdatingLocation];

}
// IOS8 新增加定位服务的代理方法
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (status == kCLAuthorizationStatusNotDetermined || status == kCLAuthorizationStatusRestricted || status == kCLAuthorizationStatusDenied ) {
        
        if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
            [self.locationManager requestWhenInUseAuthorization];
        }
        if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [self.locationManager requestAlwaysAuthorization];
        }
        
        [manager startUpdatingLocation];
        
    }
}

#pragma mark-CLLocationManagerDelegate  当定位到用户的位置时，就会调用（调用的频率比较频繁）

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    //locations数组里边存放的是CLLocation对象，一个CLLocation对象就代表着一个位置
    CLLocation *newLocation = [locations firstObject];
    NSLog(@"纬度（latitude）=%f，经度（longitude）=%f",newLocation.coordinate.latitude,newLocation.coordinate.longitude);
    
    CLGeocoder * geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark * placemark = placemarks.firstObject;
        self.locationBlock (newLocation,placemark,nil);

    }];
    //关闭定位
    if (!_isRealTime) {
        [self stopLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"Error: %@",[error localizedDescription]);
    [manager stopUpdatingLocation];
    self.locationBlock (nil,nil,error);
}

- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error
{
    self.locationBlock (nil,nil,error);
}

//高德坐标转百度坐标
//-(CLLocationCoordinate2D) googleZhuanBaiDuLatitude:(CGFloat)latitude andLongitude:(CGFloat)longitude
//{
//    CLLocationCoordinate2D test = CLLocationCoordinate2DMake(latitude, longitude);
//    //转换 google地图、soso地图、aliyun地图、mapabc地图和amap地图所用坐标至百度坐标
//    NSDictionary* testdic = BMKConvertBaiduCoorFrom(test,BMK_COORDTYPE_COMMON);
//    //转换GPS坐标至百度坐标
//    testdic = BMKConvertBaiduCoorFrom(test,BMK_COORDTYPE_GPS);
//    CLLocationCoordinate2D baiDusy =   BMKCoorDictionaryDecode(testdic);
//    return baiDusy;
//}


-(void)geocodeLocation:(CLLocationCoordinate2D)locon andLocaiontBlock:(void(^)(NSDictionary *data, NSError *error))dataBlock
{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    CLLocation *location = [[CLLocation alloc]initWithLatitude:locon.latitude longitude:locon.longitude];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count > 0 ){
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            //placemark.locality 城市 四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
            NSLog(@"------- %@",placemark.addressDictionary);
            if (placemark.addressDictionary) {
                dataBlock(placemark.addressDictionary,nil);
            }
        }else if (error == nil && [placemarks count] == 0){
            NSLog(@"No results were returned.");
        }else if (error != nil){
            NSLog(@"An error occurred = %@", error);
        }

    }];
    
}

-(void)startMapLocation
{
    if (_mapView) {
        _mapView = nil;
    }
    _mapView = [[MKMapView alloc] init];
    _mapView.delegate = self;
    _mapView.showsUserLocation = YES;
}

-(void)stopMapLocation
{
    _mapView.showsUserLocation = NO;
    _mapView = nil;
}


- (void) getMapLocationCoordinate:(LocationBlock) locaiontBlock
{
    self.locationBlock = [locaiontBlock copy];
    [self startMapLocation];
}

-(void)getMapLocationDatil:(LocationDetail)locaiontBlock
{
    self.dataBlock  =[locaiontBlock copy];
    [self startMapLocation];

}
#pragma mark-mapview delegate

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    CLLocation * newLocation = userLocation.location;

    CLGeocoder *clGeoCoder = [[CLGeocoder alloc] init];
    CLGeocodeCompletionHandler handle = ^(NSArray *placemarks,NSError *error){
        for (CLPlacemark * placeMark in placemarks){
            _addressDic =  placeMark.addressDictionary;
            _placeMark = placeMark;
            [self stopMapLocation];
        }
        
        if (_locationBlock) {
            _locationBlock(mapView.userLocation.location,_placeMark,nil);
            _locationBlock = nil;
        }
        if (self.dataBlock) {
            self.dataBlock(mapView.userLocation.location,_placeMark,_addressDic);
        }
        
    };
    [clGeoCoder reverseGeocodeLocation:newLocation completionHandler:handle];
}

- (void)mapView:(MKMapView *)mapView didFailToLocateUserWithError:(NSError *)error
{
    [self stopMapLocation];
}





@end
